<?php

class Empeval_Methods_Request_AddEmpeval {
	
	/**
	 *
	 * @var App_Methods_Data_App
	 */
	public $app;
	public $bonusGoalsFormId;
	
	public function __construct($params) {
		$this->app = new App_Methods_Data_App($params->app);
		$this->bonusGoalsFormId = $params->bonusGoalsFormId;
	}
	
	public function process() {
		$bonusGoalsFormTest = EmpevalBonusGoalsFormsQuery::create()
		->joinUserPositions()
		->with('UserPositions')
		->findOneById($this->bonusGoalsFormId);
		
		if (!($bonusGoalsFormTest instanceof EmpevalBonusGoalsForms))
			throw new Empeval_Exception_App(Empeval_Exception_Codes::INFO_BONUS_GOALS_FORM_NOT_FOUND);
		
		$bonusGoalsForm = EmpevalBonusGoalsFormsQuery::create()
			->leftJoinSummary()
			->leftJoinEmployeeEvaluations()
			->addJoinCondition('Summary', 'Summary.UserId = ' . $bonusGoalsFormTest->getUserPositions()->getUserId())
			->addJoinCondition('EmployeeEvaluations', 'EmployeeEvaluations.UserId = ' . $bonusGoalsFormTest->getUserPositions()->getUserId())
			->with('Summary')
			->with('EmployeeEvaluations')
			->findOneById($this->bonusGoalsFormId);
		
		$competanceGroups = EmpevalCompetanceGroupsQuery::create()
		->useCompetanceQuery()
			->useBehavioralIndicatorsQuery()
				->leftJoinEmployeeEvaluationValues()
				->addJoinCondition('EmployeeEvaluationValues', 'EmployeeEvaluationValues.BonusGoalsFormId = ' . $bonusGoalsForm->getId())
			->endUse()
		->endUse()
		->with('Competance')
		->with('BehavioralIndicators')
		->with('EmployeeEvaluationValues')
		->find();
		$evaluations = EmpevalEvaluationsQuery::create()->find();
		
		$con = Propel::getConnection('vgp_empeval');
		$con->beginTransaction();
		try {
			if ($bonusGoalsForm->getSummarys()->getFirst() instanceof EmpevalSummary) {
				$summary = $bonusGoalsForm->getSummarys()->getFirst();
			}
			else {
				$summary = new EmpevalSummary();
				$summary->setUserId($bonusGoalsFormTest->getUserPositions()->getUserId());
				$summary->setBonusGoalsFormId($bonusGoalsForm->getId());
				$summary->setActive(1);
				$summary->save($con);
			}
			if ($bonusGoalsForm->getEmployeeEvaluations() instanceof EmpevalEmployeeEvaluations) {
				$empeval = $bonusGoalsForm->getEmployeeEvaluations();
			}
			else {
				$empeval = new EmpevalEmployeeEvaluations();
				$empeval->setUserId($bonusGoalsFormTest->getUserPositions()->getUserId());
				$empeval->setBonusGoalsFormId($bonusGoalsForm->getId());
				$empeval->setActive(1);
				$empeval->save($con);
			}
			$con->commit();
		} catch (Exception $e) {
			$con->rollBack();
			throw $e;
		}	
		
		return new Empeval_Methods_Response_AddEmpeval(true, $summary, $empeval, $competanceGroups, $evaluations);
	}
	
}